$(function () {
    var layout = $("#zjjhgl_layout").layout();
    //======================
    //======设置查询条件========
    //======================
    //计划年份
    $("#zjjhgl_toolbar [name='jhnf']").numberspinner({
        min: 2000,
        max: 2100,
        editable: true
    });
    //计划月份
    $("#zjjhgl_toolbar [name='jhyf']").numberspinner({
        min: 1,
        max: 12,
        editable: true
    });
    //供应商
    $("#zjjhgl_toolbar [name='gys']").qyjgzcombobox();

    //统配资金计划：申报公司  申报部门  申报人
    $("#zjjhgl_toolbar [name='sbgs']").jgbmtree($("#zjjhgl_toolbar  [name='sbbm']"), null,
        $("#zjjhglForm #zgzjjh_search_sbbm").val(), null);
    //搜索按钮
    $("#zjjhgl_toolbar [name='searchButton']").click(function () {
        reloadZjjhglGrid();
    });
    //======================
    //========操作按钮========
    $("#btn_add_jkd").click(function () {
        var row = $('#zjjhgl_grid').datagrid("getSelected");
        if (row && !row.zt == 'ysp') {
            $.messager.alert("提示", "请选择已完成的资金计划!", "warning");
        }
        if (row) {
            if (row.TYPE == "Tpzjjh") {
                tpjkd_add('新增统配借款单', 'add_tpjkd');
            } else {
                zgjkd_add('新增自购借款单', 'add_zgjkd');
            }
        } else {
            $.messager.alert("提示", "请选择资金计划!", "warning");
        }
    });
    //======================
    //资金计划新增按钮
    $("#zjjhgl_toolbar [name='xzzjjh']").click(function () {
        showZjjhglDialog("新增资金计划", $.webPath() + "/jhgl/zjjhgl/zjjhgl_content", $.webPath() + "/jhgl/zjjhgl/save_zjjh");
    });

    //资金计划修改按钮
    $("#zjjhgl_toolbar [name='xgzjjh']").click(function () {
        var row = $('#zjjhgl_grid').datagrid("getSelected");
        if (row) {
            var type = row.TYPE;
            showZjjhglDialog("修改资金计划", $.webPath() + "/jhgl/zjjhgl/zjjhgl_content?id=" + row.id + "&type=" + type,
                $.webPath() + "/jhgl/zjjhgl/edit_zjjh?type=" + type);
        } else
            $.messager.alert("提示", "请选择资金计划!", "warning");
    });

    //资金计划删除按钮
    $("#zjjhgl_toolbar [name='sczjjh']").click(function () {
        var row = $('#zjjhgl_grid').datagrid("getSelected");
        if (row) {
            $.messager.confirm('确认', '是否确认删除此资金计划?', function (r) {
                if (r) {
                    zjjhAjax("/jhgl/zjjhgl/delete", row);
                }
            });
        }
        else
            $.messager.alert("提示", "请选择先选择资金计划!", "warning")
    });

    //提交审核物资计划
    $("#zjjhgl_toolbar [name='tjzjjh']").click(function () {
        var row = $('#zjjhgl_grid').datagrid("getSelected");
        if (row) {
            $.messager.confirm('确认', '是否确认提交此资金计划?', function (r) {
                if (r) {
                    zjjhAjax("/jhgl/zjjhgl/commit_zjjh", row);
                }
            });
        }
        else
            $.messager.alert("提示", "请先选择资金计划!", "warning");
    });
    //======================
    //======资金计划列表========
    //======================
    //资金计划列表
    $('#zjjhgl_grid').datagrid({
        url: $.webPath() + '/jhgl/zjjhgl/zjjhList',
        toolbar: "#zjjhgl_toolbar",
        pagination: true,
        rownumbers: true,
        singleSelect: true,
        fit: true,
        pageNumber: 1,
        fitColumns: true,
        showFooter: true,
        queryParams: {
            jhnf: $("#zjjhgl_toolbar [name='jhnf']").val(),
            jhyf: $("#zjjhgl_toolbar [name='jhyf']").val()
        },
        columns: [
            [
                {field: 'jhbh', title: '计划编号', align: 'center', width: $(this).width() * 0.1, formatter: zjjhCell},
                {field: 'gysmc', title: '供应商', align: 'center', width: $(this).width() * 0.2},
                {field: 'zjjhsbgsmc', title: '申报公司', align: 'center', width: $(this).width() * 0.1},
                {field: 'zjjhsbbmmc', title: '申报部门', align: 'center', width: $(this).width() * 0.05},
                {field: 'sbje', title: '申报金额（元）', align: 'right', width: $(this).width() * 0.2,
                    formatter: function (value) {
                        var val = formatJeForHtml2(value, ",");
                        return val;
                    }
                },
                {field: 'sbr', title: '制单人', align: 'center', width: $(this).width() * 0.1},
                {field: 'sbrq', title: '申报时间', align: 'center', width: $(this).width() * 0.1},
                {field: 'ZT', title: '状态', align: 'center', width: $(this).width() * 0.1,
                    formatter: formatZjjhglZT
                }
            ]
        ],
        onSelect: function (rowIndex, rowData) {
            var id = rowData.id;
            var type = rowData.TYPE;
            var col = null;
            //操作按钮的显示
            if (type == "Tpzjjh") {
                $("#mod_zjjh").show();
                $("#del_zjjh").show();
                $("#commit_check").show();
                $("#btn_add_jkd").show();
            }
            if (type == "Zgzjjh") {
                $("#mod_zjjh").show();
                $("#del_zjjh").show();
                $("#commit_check").show();
                $("#btn_add_jkd").show();
            }

            if (rowData.ZT == 'ybc') {
                $("#zjjhgl_toolbar [name='xzzjjh']").css('display', '');
                $("#zjjhgl_toolbar [name='xgzjjh']").css('display', '');
                $("#zjjhgl_toolbar [name='sczjjh']").css('display', '');
                $("#zjjhgl_toolbar [name='tjzjjh']").css('display', '');
                $("#btn_add_jkd").hide();
            } else if (rowData.ZT == 'ysp') {
                $("#zjjhgl_toolbar [name='xzzjjh']").css('display', '');
                $("#zjjhgl_toolbar [name='xgzjjh']").css('display', 'none');
                $("#zjjhgl_toolbar [name='sczjjh']").css('display', 'none');
                $("#zjjhgl_toolbar [name='tjzjjh']").css('display', 'none');
                $("#btn_add_jkd").show();
            } else {
                $("#zjjhgl_toolbar [name='xzzjjh']").css('display', '');
                $("#zjjhgl_toolbar [name='xgzjjh']").css('display', 'none');
                $("#zjjhgl_toolbar [name='sczjjh']").css('display', 'none');
                $("#zjjhgl_toolbar [name='tjzjjh']").css('display', 'none');
                $("#btn_add_jkd").hide();
            }
        },
        onLoadSuccess: function () {
            $("#mod_zjjh").hide();
            $("#del_zjjh").hide();
            $("#commit_check").hide();
            $("#btn_add_jkd").hide();
            var rows = $('#zjjhgl_grid').datagrid("getRows");
            if (rows.length > 0) {
                $('#zjjhgl_grid').datagrid("selectRow", 0);
            }

            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        }, onDblClickCell: function (index, field, value) {
            if (field == "jhbh") {
                $("#mod_zjjh:visible").click();
            }
        }
    });

    //自购资金计划列
    var zgzjjhmxCol = [
        {title: '付款日期', field: 'fkrq', align: 'center', width: 150},
        {title: '付款金额', field: 'fkje', align: 'right', width: 150,
            formatter: function (value) {
                var val = formatMoney(value);
                return val;
            }}
    ];
    //统配资金计划列
    var tpzjjhmxCol = [
        {title: '品名', field: 'pm.name', align: 'center', width: 150},
        {title: '核定数量', field: 'hdsl', align: 'right', width: 150},
        {title: '付款日期', field: 'fkrq', align: 'center', width: 150},
        {title: '付款金额', field: 'fkje', align: 'right', width: 150,
            formatter: function (value) {
                var val = formatMoney(value);
                return val;
            }
        }
    ];

    //新增统购电子借款单
    function tpjkd_add(title, action) {
        var row = $('#zjjhgl_grid').datagrid("getSelected");
        if (!row) {
            $.messager.alert("提示", "请先选统配择资金计划!", "warning");
            return;
        }
        var href = $.webPath() + "/jhgl/zjjhgl/add_tpjkd?id=" + row.id;
        var actionUrl = $.webPath() + "/jhgl/zjjhgl/add_jkd";
        jkd_showDialog(title, href, actionUrl);
    }

    //新增自购电子借款单
    function zgjkd_add(title, action) {
        var row = $('#zjjhgl_grid').datagrid("getSelected");
        if (!row) {
            $.messager.alert("提示", "请先选择统配资金计划!", "warning");
            return;
        }
        var href = $.webPath() + "/jhgl/zjjhgl/add_zgjkd?id=" + row.id;
        var actionUrl = $.webPath() + "/jhgl/zjjhgl/add_jkd";
        jkd_showDialog(title, href, actionUrl);
    }

    //弹出新增或修改的窗口
    function jkd_showDialog(title, href, actionUrl) {
        var win = $.window({
            title: title,
            width: 750,
            height: 430,
            iconCls: 'icon-add2',
            cache: false,
            url: href,
            modal: true,
            onMaximize: function () {
                $(this).find("#zjjhgl_tabs").tabs("resize");
                //   $(this).find("#wzjhgl_wzjhmx_edatagrid").edatagrid("resize");

            },
            onRestore: function () {
                $(this).find("#zjjhgl_tabs").tabs("resize");
                // $(this).find("#wzjhgl_wzjhmx_edatagrid").edatagrid("resize");
            },
            buttons: [
                {
                    text: '确认',
                    handler: function () {
                        $(win).mask();
                        $('#form_jkd').form('submit', {
                            url: actionUrl,
                            onSubmit: function () {
                                var isValid = $(this).form('validate');
                                if (!isValid) {
                                    $(win).mask('hide');
                                    return false;
                                }
                                return isValid;
                            },
                            success: function (data) {
                                $(win).mask('hide');
                                var json = $.parseJSON(data);
                                if (json.statusCode == 200) {
                                    $(win).window('close');
                                    $('#zjjhgl_grid').datagrid('reload');
                                    $('#zjjhgl_layout').layout('panel', 'center').panel('refresh');
                                    $.messager.show({
                                        title: '提示',
                                        msg: json.message,
                                        timeout: 3000,
                                        showType: 'slide'
                                    });
                                } else
                                    $.messager.alert('提示', json.message, 'error');
                            }
                        });
                    }
                }
            ]
        });
    }

    //刷新表格
    function reloadZjjhglGrid() {
        $('#zjjhgl_grid').datagrid('reload', {
            type: $("#zjjhgl_toolbar [name='zjjhlb']").val(),
            jhbh: $("#zjjhgl_toolbar [name='jhbh']").val(),
            sbgsId: $("#zjjhgl_toolbar [name='sbgs']").val(),
            sbbmId: $("#zjjhgl_toolbar [name='sbbm']").val(),
            jhnf: $("#zjjhgl_toolbar [name='jhnf']").val(),
            jhyf: $("#zjjhgl_toolbar [name='jhyf']").val(),
            gysId: $("#zjjhgl_toolbar [name='gys']").val(),
            zt: $("#zjjhgl_toolbar [name='zt']").val()
        });
    }

    function zjjhAjax(url, row) {
        var type = row.TYPE;
        $.ajax({
            url: $.webPath() + url,
            dataType: 'json',
            type: 'POST',
            data: {
                id: row.id,
                type: type
            },
            beforeSend: function () {
                $("#zjjhgl_layout").mask();
            },
            success: function (data) {
                $("#zjjhgl_layout").mask("hide");
                if (data.statusCode == 200) {
                    reloadZjjhglGrid();
                    $.messager.show({
                        title: '提示',
                        msg: data.message,
                        timeout: 3000,
                        showType: 'slide'
                    });
                } else {
                    $.messager.alert('提示', data.message, 'error');
                }
            },
            error: function () {

            }
        });
    }

    //资金计划弹出框
    function showZjjhglDialog(title, href, actionUrl) {
        var win = $.window({
            title: title,
            iconCls: 'icon-add2',
            width: 850,
            height: 470,
            maximizable: true,
            cache: false,
            url: href,
            modal: true,
            onMaximize: function () {
                $(this).find("#zjjhglForm").tabs("resize");
                $(this).find("#zjjhgl_zjjhmx_edatagrid").edatagrid("resize");

            },
            onRestore: function () {
                $(this).find("#zjjhglForm").tabs("resize");
                $(this).find("#zjjhgl_zjjhmx_edatagrid").edatagrid("resize");
            },
            buttons: [
                {
                    text: '保存',
                    handler: function () {
                        $(win).mask();
                        $('#zjjhglForm').form('submit', {
                            url: actionUrl,
                            onSubmit: function (param) {
                                //结束编辑列的编辑状态
                                var r = $('#zjjhglForm #zjjhgl_zjjhmx_edatagrid').edatagrid("getSelected");
                                var index = $('#zjjhglForm #zjjhgl_zjjhmx_edatagrid').edatagrid("getRowIndex", r);
                                $('#zjjhglForm #zjjhgl_zjjhmx_edatagrid').edatagrid("endEdit", index);
                                //验证主信息表单
                                var isValid = $(this).form('validate');
                                if (!isValid) {
                                    $(win).mask('hide');
                                    $('#zjjhglForm').tabs('select', 0);
                                    return false;
                                }
                                //验证明细列表
                                var data = $('#zjjhglForm #zjjhgl_zjjhmx_edatagrid').edatagrid("getData");
                                if (!data.rows.length) {
                                    $(win).mask('hide');
                                    $.messager.alert("提示", "请填写资金计划明细!", "waring");
                                    $('#zjjhglForm').tabs('select', 1);
                                    return false;
                                } else {
                                    var checkedRadio = $("#zjjhglForm [name='type']:checked").val();
                                    var zjjhType = "";

                                    var jhnf , jhyf;
                                    if (checkedRadio == "Zgzjjh") {
                                        zjjhType = "自购";
                                        jhnf = $("#zgzjjh_jhnf").val();
                                        jhyf = $("#zgzjjh_jhyf").val();
                                    } else if (checkedRadio == "Tpzjjh") {
                                        zjjhType = "统配";
                                        jhnf = $("#tpgzjjh_jhnf").val();
                                        jhyf = $("#tpgzjjh_jhyf").val();
                                    }


                                    for (var i = 0; i < data.rows.length; i++) {
                                        var fkrq = data.rows[i].fkrq;
                                        if (data.rows[i].fkrq == "") {
                                            $(win).mask('hide');
                                            $.messager.alert("提示", "请填写" + zjjhType + "资金计划付款日!", "waring");
                                            $('#zjjhglForm').tabs('select', 1);
                                            return false;
                                        }
                                        if (parseFloat(data.rows[i].fkje) == 0) {
                                            $(win).mask('hide');
                                            $.messager.alert("提示", "请填写" + zjjhType + "资金计划付款金额!", "waring");
                                            $('#zjjhglForm').tabs('select', 1);
                                            return false;
                                        }
                                        var fknf = fkrq.split("-")[0];
                                        var fkyf = fkrq.split("-")[1];

                                        if (fkyf[0] == 0)
                                            fkyf = fkyf[1];
                                        if (parseInt(fknf) != parseInt(jhnf) || parseInt(fkyf) != parseInt(jhyf)) {
                                            $(win).mask('hide');
                                            $.messager.alert("提示", zjjhType + "资金计划付款日期不在需求日期范围内!", "waring");
                                            $('#zjjhglForm').tabs('select', 1);
                                            return false;
                                        }
                                    }
                                }

                                var checkedRadio = $("#zjjhglForm [name='type']:checked").val();
                                var arrayPrefix = null;
                                var objectPrefix = null;
                                if (checkedRadio == "Zgzjjh") {
                                    arrayPrefix = "zgzjjhmxList";
                                    objectPrefix = "zgzjjh";
                                }
                                if (checkedRadio == "Tpzjjh") {
                                    arrayPrefix = "tpzjjhmxList";
                                    objectPrefix = "tpzjjh";
                                }
                                var paramString = "{"
                                //资金计划明细
                                for (var i = 0; i < data.rows.length; i++) {
                                    var objectString = $.toJSONStringPrefix(data.rows[i], arrayPrefix + "[" + i + "].");
                                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                                }
                                var footer = $('#zjjhglForm #zjjhgl_zjjhmx_edatagrid').datagrid('getFooterRows');
                                paramString = paramString + "\"" + objectPrefix + ".sbje\":" + $(footer).get(0).fkje;
                                paramString = paramString + "}";
                                $.extend(param, $.parseJSON(paramString));

                                if (isValid)
                                    $(win).mask();
                                return isValid;
                            },
                            success: function (data) {
                                $(win).mask('hide');
                                var json = $.parseJSON(data);
                                if (json.statusCode == 200) {
                                    $(win).dialog('close');
                                    reloadZjjhglGrid();
                                    $('#zjjhgl_layout').layout('panel', 'center').panel('refresh');
                                    $.messager.show({
                                        title: '提示',
                                        msg: json.message,
                                        timeout: 3000,
                                        showType: 'slide'
                                    });
                                } else {
                                    $.messager.alert('提示', json.message, 'error');
                                }
                            }
                        });
                    }
                }
            ]
        });
        $(win).dialog('open');
    }
});
function formatZjjhglZT(val, row) {
    if (val == 'ybc')
        val = '已保存';
    if (val == 'ytj')
        val = '已提交';
    if (val == 'ysp')
        val = '已审批';

    if (!row.processInstanceId) {
        return val;
    } else {
        return '<a href="javascript:viewZjjhglFlowPicture();" style="color: red">' + val + '</a>';
    }
}

function viewZjjhglFlowPicture() {
    var row = $('#zjjhgl_grid').datagrid("getSelected");
    $.window({
        title: "流程历史",
        iconCls: 'icon-add2',
        url: $.webPath() + "/flow/publish/flowPicture?processInstanceId=" + encodeURI(encodeURI(row.processInstanceId)) + "&businessNo=" + row.jhbh,
        width: 650,
        height: 500,
        closed: true,
        modal: true,
        isMax: true
    });
}